const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);
const sdate = require('silly-datetime');

const {
    getTaskPage,
    wxpusher,
} = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
    getProxy,
    getIp,
    getIp_v3,
    httpProxyGet,
} = require('./util');

const {
    get,
    easyPushWechatMsg,
    lpush,
    set,
    hget,
    hset,
    expire,
    hgetall,
    randBetween,
    avoidNoticeFreq,
} = require('../util');

const {
    syncExec,
    syncExec2
} = require('../model'); 

process.on('unhandledRejection', error => {
    //...不处理...
});

const serialMap = {};//已启动到任务

let ip_list = [];

let arguments = process.argv.splice(2);

const getProxySlow = async () => {
    let proxy = '';

    const key = 'new1_proxy_list_'+arguments[0];
    let proxy_list = await get(key);

    if(proxy_list){
        ip_list = JSON.parse(proxy_list);
    }else{
        ip_list = [];
    }

    if(ip_list.length == 0){
        ip_list = await getIp_v3(99);

        if(!ip_list){
            await sleep(2000);
            ip_list = await getIp_v3(99);
        }
        await set(key, JSON.stringify(ip_list));
        await expire(key, 60*5);
    }

    //logger('ip_list', ip_list);



    return ip_list;
}

//每N秒重新拉取任务列表
(async () => {
    const url = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn=';

    while (1) {

        const tasks = await readTask(arguments[0],65);
        if (!tasks) {
            await sleep(5000);
            continue;
        }

        //const tasks = [{ taskid: 1, taskId: 1, serial: 'INA128HD', status: 1 }];

        //console.log(tasks);


        const taskSerials = [];

        let counter = 0;

        let task_index = 0;
        //启动任务
        for (const task of tasks) {
            if (task.status != 1) continue;
            taskSerials.push(task.serial);

            if (!serialMap[task.serial]) {
                serialMap[task.serial] = 1;

                let proxy_list = await getProxySlow();

                (async (serial, proxy_list, counter) => {
                    if (counter % 10 > 0) {
                        await sleep(counter % 10 * 1000);
                    }
                    logger(counter, serial, '启动');
                    let index = (counter-1) % proxy_list.length;

                    logger('index', index);
                    let proxy = proxy_list[index];

                    while (1) {
                        if (!serialMap[serial]) {
                            logger(serial, '关闭');
                            return;
                        }

                        try {
                            const fullUrl = url + encodeURIComponent(serial);
                            let str = '';
                            let ret = '';
                            str = await httpProxyGet(fullUrl, proxy);
                            ret = JSON.parse(str);

                            const today = sdate.format(new Date(), 'YYYY-MM-DD');
                            const serial_data_key = 'serial_data_'+ today;
                            let serial_data = await hget(serial_data_key, serial);

                            serial_data = JSON.parse(serial_data);

                            if(!serial_data){
                                serial_data = {'serial':task.serial, 'last_stock_num':0, 'last_has_stock_time':'', 'last_check_time':'', 'check_num':0, 'worker':'机器'+arguments[0], 'proxy':proxy};
                            }

                            logger(ret);
                            const stock = ret.inventory;

                            serial_data.last_check_time = sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                            serial_data.check_num = serial_data.check_num + 1;
                            serial_data.worker = '机器'+arguments[0];
                            serial_data.proxy = proxy;

                            if (stock >= 250) {
                                serial_data.last_has_stock_time = sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                                serial_data.last_stock_num = stock;
                            }

                            await hset(serial_data_key, serial, JSON.stringify(serial_data));

                            if (stock >= 250) {

                                const success_log_key = 'success_log_'+ today;
                                await lpush(success_log_key, JSON.stringify({'serial':serial, 'stock':stock, 'time':sdate.format(new Date(), 'YYYY-MM-DD HH:mm:ss')}));

                                const msg = `全查方案：规格 ${serial} 发现有 ${stock} 库存可以下单`;
                                if (await avoidNoticeFreq(serial)) {
                                    await easyPushWechatMsg(msg);
                                }
                                logger(msg);

                                try {

                                    const cookie = await get('ti_worker_cookie');

                                    const cmdStr = `curl --compressed -H 'Host: www.ti.com.cn' -H 'Connection: keep-alive' -H 'sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"'  -H 'sec-ch-ua-mobile: ?0'   -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" -H "Content-Type: application/json" -H 'X-Sec-Clge-Req-Type: ajax' -H 'Expires: 0' -H "Cache-Control: no-store, must-revalidate" -H 'sec-ch-ua-platform: "macOS"' -H 'Accept: */*' -H 'Origin: https://www.ti.com.cn' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Dest: empty' -H 'Referer: https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'Cookie: ${cookie}' -d '{"cartRequestList":[{"packageOption":null,"opnId":"${serial}","quantity":"${stock}","tiAddtoCartSource":"store-pdp","sparam":""}],"currency":"CNY"}'  https://www.ti.com.cn/occservices/v2/ti/addtocart`;

                                    const recentSuccKey = 'ti_add_cart_succ_'+serial;
                                    const isRecentSucc = await get(recentSuccKey);
                                    //最近加购物车是否失败
                                    const recentFailKey = 'ti_add_cart_fail_'+serial;
                                    const isRecentFail = await get(recentFailKey);

                                    if (!isRecentSucc && !isRecentFail) {

                                        ret = await syncExec(cmdStr);


                                        if (ret.indexOf('cartId') > -1) {
                                            const msg = `全查方案：${serial}加购物车${stock}成功`;
                                            logger(msg, ret);
                                            //推送微信通知
                                            await easyPushWechatMsg(msg);

                                            //推送到redis，等待下单脚本进行下单操作
                                            await lpush('ti_worker_order', serial);

                                            //记录到redis，最近1小时不再尝试加购物车
                                            await set(recentSuccKey, 1);
                                            await expire(recentSuccKey, 3600);
                                        }else if(ret.indexOf('Access') > -1 && ret.indexOf('Denied') > -1){
                                            if (await avoidNoticeFreq(serial)) {
                                                //await easyPushWechatMsg("全查方案：请在后台更换cookie");
                                            }
                                        }
                                    }

                                    

                                } catch(e) {
                                    logger(e);
                                }
                                await sleep(10000);
                            }
                            await sleep(6000);
                        } catch(e) {
                            logger(e);
                            logger('test--'+proxy+' '+serial+' ');
                            await sleep(2000);
                            let tmp_index = randBetween(0, proxy_list.length);
                            proxy = proxy_list[tmp_index];
                            continue;
                        }
                    }
                })(task.serial, proxy_list, counter++);
            }
        }

        //关闭任务
        for (const serial in serialMap) {
            if (taskSerials.indexOf(serial) < 0) {
                delete serialMap[serial];
            }
        }

        await sleep(30000);
    }
})();